;(function($,window){

    // 管道
    var $pipeline = $('#JQ_pipeline').select3();
    // 管段
    var $segment = $('#pipeSegmentArr').select3({
        title: '管段'
    });
    //高后果区等级

    var $high = $('#high').select3();
    DyyBase.ajax(DyyBase.root_path+'/comm/codes.json?majorCode=HAC_GRADE',{},function(data){
        var json = DyyBase.getSelect(data.result);
        json.shift();
        $high.add(json);
    });

    // 起点位置
    var $begin = $('#JQ_begin').select3({
        title: '起点位置',
        server: true,
        mileType: 'float',
        param: {'pipeLineId': $pipeline, 'pipeSegmentId': $segment}
    });
    // 终点位置
    var $end = $('#JQ_end').select3({
        title: '终点位置',
        server: true,
        mileType: 'float',
        param: {'pipeLineId': $pipeline, 'pipeSegmentId': $segment, 'beginSignId': $begin}
    });

    //触发管道
    $pipeline.element.on('select', function (e, v) {
        var id = v || $pipeline.val();
        if (id) {
            // 管段
            DyyBase.ajax(DyyBase.url_segment(), {pipeLineId: id}, function (dataset) {
                var json = DyyBase.getSelect(dataset);
                $segment.add(json);
            });
            // 起点 & 终点
            DyyBase.ajax(DyyBase.url_pipe_pos(), {pipeLineId: id}, function (dataset) {
                var begin = DyyBase.getPos(dataset, 'begin', true);
                var end = DyyBase.getPos(dataset, 'end',true);
                $begin.add(begin);
                $end.add(end);
            });

        } else {
            $segment.add([]);
            $begin.add([]);
            $end.add([]);
        }
    });
    //触发管段
    $segment.element.on('select', function (e, v) {
        var id = v || $segment.val();
        if (id) {
            // 起点 & 终点
            DyyBase.ajax(DyyBase.url_segment_pos(), {pipeSegmentId: id}, function (dataset) {
                var begin = DyyBase.getPos(dataset, 'begin',true);
                var end = DyyBase.getPos(dataset, 'end',true);
                $begin.add(begin);
                $end.add(end);
            });
        } else {
            $begin.add([]);
            $end.add([]);
        }
    });
    // 初始化日期控件
    var $date_01 = $('#JQ_input_date_01');
    var $date_02 = $('#JQ_input_date_02');

    // 搜索条件
    var filter = {
        // 获得表单项
        getCondition: function(param){
            var data = {};
            data.mode = true;
            // 分页参数
            if (param) {
                if (param.start == 0) {
                    data['jsonBean.pageNum'] = 1;
                } else {
                    data['jsonBean.pageNum'] = param.start / 10 + 1;
                }
                data['jsonBean.pageCount'] = param.length;
            }
            data.startDate = function(){
                var v=$date_01.val();
                if(v){
                    return v;
                }
                return '';
            }();
            //结束时间
            data.endDate=function(){
                var v1 = $date_01.val();
                var v2 = $date_02.val();
                if (v2) {
                    if (!(Dyy.checkDateLate(v1, v2))) {
                        $date_02.TIP({content: '结束时间须晚于开始时间!'});
                        data.mode = false;
                    }
                    return v2;
                }
                return '';
            }();
            // 管道id
            data.pipeLineId = function(){
                var v=$pipeline.val();
                if (v){
                    return v;
                }
                return '';
            }();
            //高后果等级
            data.hacGrade=function(){
                var v=$high.val();
                if(v){
                    return v;
                }
                return '';
            }();
            //起点绝对距离
            data.fromMileage=function(){
                var v= $begin.val('mile');
                if (DyyBase.notEmpty(v)){
                    return v;
                }
                return '';
            };
            //终点绝对距离
            data.toMileage=function(){
                var v= $end.val('mile');
                if (DyyBase.notEmpty(v)){
                    return v;
                }
                return '';
            };
            return data;
        },
        //导出返回参数
        getExport:function(){
            var dataExportV = {};
            dataExportV.pipeLineId = function(){
                var v=$pipeline.val();
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.pipeLineName = function(){
                var v=$pipeline.val('text');
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.startDate=function(){
                var v=$date_01.val();
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.endDate=function(){
                var v=$date_02.val();
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.hacGrade=function(){
                var v=$high.val();
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.fromMileage=function(){
                var v=$begin.val('mile');
                if(v){
                    return v;
                }
                return '';
            }();
            dataExportV.toMileage=function(){
                var v=$end.val('mile');
                if(v){
                    return v;
                }
                return '';
            }();
            return dataExportV;
        },
        // 执行查询后的筛选对象
        getExportFilter: function(){
            return filter.getCondition();
        }
    };
    // 初始化表格数据
    var $table_01 = $('#JQ_datatable_01').checkbox3();
    var DTHCA = $table_01.DataTable({
        'language': {
            'paginate': {
                'next': '下一页',
                'previous': '上一页'
            },
            'info': '本次检索共 _TOTAL_ 条，每页显示 10 条，共 _PAGES_ 页 ',
            'lengthMenu': '每页显示 _MENU_ 条',
            'search': '搜索',
            'searchPlaceholder': '输入名称',
            'zeroRecords': function(){
                // 无数据
                return '<div class="zy-datatable-empty"><p><img src="' + DyyBase.root_path + '/static/img/no_data.png"></p><h2>管道管理的太好了！</h2><p class="c-90">未发现漏损点</p></div>';
            },
            'infoEmpty':'',
            'infoFiltered': ' - 从 _MAX_ 条数据中搜索',
            'loadingRecords': '等待载入数据...'
        },
        'autoWidth': false,
        'serverSide': true,
        'pageLength': 10,
        'ordering': false,
        'processing': false,
        'searching': false,
        'lengthChange': false,
        'ajax': function(data, callback){
            // 查询数据
            var param = filter.getCondition(data);
            DyyBase.ajax(RiskComm.local_path()+"/riskMgr/hca/queryHca.json",param,function(dataset){

                // 封装返回数据
                var returnData = {};
                returnData.draw = data.draw;
                returnData.recordsTotal = dataset.result.total;
                returnData.recordsFiltered = dataset.result.total;
                returnData.data = dataset.result.list;

                // 回调渲染
                callback(returnData);
            });
        },
        'drawCallback': function(settings){
            // 渲染
        },
        'columns': [
            {'data': 'pipeLineName',render:function(data, type, row){
                return '<span title="'+data+'">'+data+'</span><input name="data_gis_id" type="hidden" value="'+row.gisId+'">';
            }},
            {'data': 'hacGrade',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'hcaLength',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'fromLocationDescription',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'toLocationDescription',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'threatScore',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'description',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'influenceRadius',render:function(data){
                return '<span title="'+data+'">'+data+'</span>';
            }},
            {'data': 'id',render:function(data){
                return '<i data-defectId="'+data+'" class="zy-details-icon" title="详情"></i>';
            }}
        ]
    });
    // 展开详情
    $table_01.delegate('i.zy-details-icon','click',function(){
        // 当前按钮
        var $this_i = $(this);
        // 携带的ID
        var defectId = $this_i.attr('data-defectId');
        // 当前父级 tr
        var $tr = $this_i.parent('td').parent('tr');
        // 当前父级 tbody
        var $tbody = $this_i.parent('td').parent('tr').parent('tbody');
        // 已经存在的动态 tr ?
        var $dy_tr = $tbody.find('tr[data-defectId="'+defectId+'"]');

        // 激活当前按钮选中样式
        $table_01.find('i.zy-details-icon').removeClass('active');
        $this_i.addClass('active');

        // 隐藏其他动态行
        $table_01.find('tr.zy-dy-tr').hide();

        // 有则显示 无则填充
        if($dy_tr.length > 0){
            $dy_tr.show();
        }else{
            fillAdviseDetails($tr,defectId);
        }
    });
    // 收起详情
    $table_01.delegate('button.zy-pack-up','click',function(){
        var $this_btn = $(this);
        var defectId = $this_btn.attr('data-defectId');
        $table_01.find('tr[data-defectId="'+defectId+'"]').hide();
        $table_01.find('i.zy-details-icon').removeClass('active');
    });

    // 填充详情
    function fillAdviseDetails(tr,id){
        var data_row = DTHCA.row(tr).data(); // 行数据
        data_row = DyyBase.clearNull(data_row);

        var $dy_tr = $('<tr class="zy-dy-tr" data-defectId="'+id+'"><td colspan="9"><div class="zy-details-box"></div></td></tr>');
        var $dy_box = $dy_tr.find('div.zy-details-box');
        var html = '<div class="zy-dy-inner"><div class="zy-dy-p">'
            +'<p>统一编号：'+data_row.code+'</p>'
            +'<p>管道名称：'+data_row.pipeLineName+'</p>'
            +'<p>高后果区编号：'+data_row.hcaNumber+'</p>'
            +'<p>高后区长度(m)：'+data_row.hcaLength+'</p>'
            +'<p>起始绝对里程：'+data_row.fromMileage+'</p>'
            +'<p>起始最终参考点：'+data_row.fromReference+'</p>'
            +'<p>起始相对最近参考点距离（m）：'+data_row.fromReferenceDistance+'</p>'
            +'<p>终点绝对里程：'+data_row.toMileage+'</p>'
            +'<p>终点最终参考点：'+data_row.toReference+'</p>'
            +'<p>终点相对最近参考点距离（m）：'+data_row.toReferenceDistance+'</p>'
            +'<p>起点位置描述：'+data_row.fromLocationDescription+'</p>'
            +'<p>终点位置描述：'+data_row.toLocationDescription+'</p>'
            +'<p>评价时间：'+data_row.riskDate+'</p>'
            +'<p>可能存在的威胁总分：'+data_row.threatScore+'</p>'
            +'<p>高后果区描述：'+data_row.description+'</p>'
            +'<p>高后果区等级：'+data_row.hacGrade+'</p>'
            +'<p>潜在影响半径（m）：'+data_row.influenceRadius+'</p>'
            +'<p>记录人：'+data_row.recrder+'</p>'
            +'<p>记录时间：'+data_row.recordTime+'</p>'
            +'<p>备注：'+data_row.remark+'</p>'
            +'<div class="clear"></div>'
            +'</div><div class="zy-dy-footer" style="padding:0 0 20px 0"><button data-defectId="'+id+'" class="zy-button zy-pack-up" type="button" style="background-color: white"><i></i>收起</button></div></div>';
        // 内部装入 html
        $dy_box.html(html);
        // 后方插入 tr
        tr.after($dy_tr);
    };
    // 搜索
    $('#JQ_search_hca').on('click', function() {
        var param = filter.getCondition();
        if (param.mode) {
            if (DTHCA) {
                DTHCA.draw();
            }
        }
    });
    // 导出
    $('#btn_export').click(function () {
        var param = filter.getExport;
        if(param instanceof Function){
            param = param();
        }
        $(this).EXPT({
            type: 'name',
            name: param.pipeLineName+'高后果区数据',
            param: param,
            server: DyyBase.root_path +　'/riskMgr/hca/export.json'

        });
    });

    // gis地图
    $('#JQ_gis_btn').on('click', function() {
        localRiskGis();
    });

    //统计
    $("#sta_hac").on('click',function(){
        window.location.href=DyyBase.root_path+'/riskMgr/hca/toStatistics.html';
    });

    // 导出文件
    //function riskExport() {
    //    //DyyBase.search = true;
    //    //var v = filter.getCondition();
    //    //console.log(v);
    //
    //    var form = createForm(RiskComm.local_path()+ '/riskMgr/hca/export.json');
    //    form.submit();
    //    form.remove();
    //}
    //
    //function createInput(obj) {
    //    var _name = obj.name;
    //    var _value = obj.value;
    //
    //    var _input = $('<input>');
    //    _input.attr('type', 'hidden');
    //    _input.attr('name', _name);
    //    _input.attr('value', _value);
    //    return _input;
    //}
    //
    //function createForm(actionUrl) {
    //    var form = $("<form>");
    //    form.attr('style', 'display:none');
    //    form.attr('target', '');
    //    form.attr('method', 'post');
    //    form.attr('action', actionUrl);
    //    $('body').append(form);
    //    form.append(createInput({name:"pipeLineId", value:$pipeline.val()}));
    //    //form.append(createInput({name:"pipeSegmentIdSearch", value:$("#pipeSegmentSearch").find("a").attr("id")}));
    //    form.append(createInput({name:"startDate", value:$date_01.val()}));
    //    form.append(createInput({name:"endDate", value:$date_02.val()}));
    //    form.append(createInput({name:"hacGrade", value:$high.val()}));
    //    form.append(createInput({name:"fromMileage", value:$begin.val('mile')}));
    //    form.append(createInput({name:"toMileage", value:$end.val('mile')}));
    //
    //    return form;
    //}

    /* 页面跳转 */
    function localRiskGis(){

        $("#showGis").show();
        var arr = [];
        var $data = $('input[name="data_gis_id"]');
        var $form = $('#JQ_gis_form');
        $data.each(function(){
            var $this = $(this);
            arr.push($this.val());
        });
        var $input = $('<input type="hidden">');
        $input.prop('name','gisArray').val(arr.join(','));
        $form.append($input);
        $form.submit();
        /*$.each(data, function(i) {
         //_gis_array.push(data[i].value);
         var $input = $('<input type="hidden">');
         $input.prop('name',).val();
         });*/


    }

    /* 高后果区已经评价占的百分比 */
    function statisticsPercent(){
        DyyBase.search = true;
        var param = filter.getCondition();
        $.post(RiskComm.local_path()+"/riskMgr/hca/statistics.json",
            param,
            function (data) {
                var _data = $.parseJSON(data);
                var _result = _data.result;
                console.log("==============>"+_result);
                _result = _result > 1 ? 100 : _result * 100;
                $("#statisticsPercent").html(_result+"%");
                $('.jdt .s1 em').css({width:$('.xifan').html()})
            }
        );
    }
})(jQuery,window);